package com.lzy.shops.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzy.shops.bean.Goods;
import com.lzy.shops.service.ShowGoodsService;
import com.lzy.shops.utils.ResponseData;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/showGoods")
public class showGoodsController {

    @Autowired
    private ShowGoodsService service;

    private ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/index/findAll")
    public String findAll(@RequestParam("u1") String start,@RequestParam("u2") String end,@RequestParam("t") String type) throws JsonProcessingException {
        ResponseData<Object> responseData = null;
        try {
            if(type.equals("")){
                type = "phone";
            }
            List<Goods> all = service.findAll(type,Integer.parseInt(start), Integer.parseInt(end));
            responseData = new ResponseData<Object>(true,all);
        } catch (NumberFormatException e) {
            responseData = new ResponseData<Object>(false,e.getMessage());
        }
        return objectMapper.writeValueAsString(responseData);
    }

    @GetMapping("/index/findById/{shopId}")
    public String findById(@PathVariable("shopId") String id) throws JsonProcessingException {
        ResponseData<Object> responseData = null;
        try {
            int shopId = Integer.parseInt(id);
            if(shopId>0&&shopId!=0){
                Goods goods = service.findById(shopId);
                if(goods!=null){
                    responseData = new ResponseData<Object>(true,goods);
                }else throw new RuntimeException("数据异常");
            }else throw new RuntimeException("参数传递异常");
        } catch (Exception e) {
            responseData = new ResponseData<Object>(false,e.getMessage());
        }
        return objectMapper.writeValueAsString(responseData);
    }

}
